package com.dayatang.android.Activity;

import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.TextAppearanceSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.dayatang.android.Activity.Application.MyApplication;
import com.dayatang.android.Model.Project;
import com.dayatang.android.Model.ProjectSearchLog;
import com.dayatang.android.Task.ProjectSearchTask;
import com.dayatang.android.config.Config;

public class ProjectDetailActivity extends FootCommonActivity {
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AlabSetContentView(R.layout.project_detail_activity);
		doIntent();
		InitRealWorkload();
		InitFinishOutputValue();
		InitProjectBasicInfo();
		AlabSetBarTitleText(getCurProject().getName());
	}
	
	private void InitProjectBasicInfo() {
		
		Project project = getCurProject();
		String[] info = {getString(R.string.subproject_expenditure_all),getString(R.string.subproject_basic_project_type),getString(R.string.subproject_basic_contract_number),project.getExpenditure()+getString(R.string.subproject_finish_output_unit),project.getProjectType(),project.getContractNumber(),getString(R.string.subproject_basic_startdate),getString(R.string.subproject_basic_finishdate),getString(R.string.subproject_basic_project_area),project.getStartDate(),project.getFinishDate(),project.getArea(),getString(R.string.subproject_basic_subproject_num),getString(R.string.subproject_basic_suproject_finished_num),getString(R.string.subproject_basic_responsible_division),project.getSubProjectNum(),project.getSubProjectFinishedNum(),project.getResponsibleDivision()};
		
		boolean one = true;
		for (int i = 0; i < info.length; i = i + 3) {
			if (one) {
				InitTableLayout(info[i],info[i+1],info[i+2],"white",R.id.subproject_basic_information_tablelayout);
				one = false;
			} else {
				InitTableLayout(info[i],info[i+1],info[i+2],"black",R.id.subproject_basic_information_tablelayout);
				one = true;
			}
		}
		
		String[] aboutInfo = {getString(R.string.subproject_about_organization_ownerinfo),getString(R.string.subproject_about_organization_supervisorinfo),getString(R.string.subproject_about_organization_designerinfo),project.getOwnerInfo(),project.getSupervisorInfo(),project.getDesignerInfo()};
		
		for (int i = 0; i < aboutInfo.length; i = i + 3) {
			if (one) {
				InitTableLayout(aboutInfo[i],aboutInfo[i+1],aboutInfo[i+2],"white",R.id.subproject_about_organization_tablelayout);
				one = false;
			} else {
				InitTableLayout(aboutInfo[i],aboutInfo[i+1],aboutInfo[i+2],"black",R.id.subproject_about_organization_tablelayout);
				one = true;
			}
		}
	}
	
	
	private void InitFinishOutputValue() {
		
		String data = getCurProject().getSpecialtyOutput();
		
		long outputAll = 0;
		
		try {
			JSONArray jsonArray = new JSONArray(data);
			for(int i = 0; i < jsonArray.length(); i++) {
				
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				
				InitTableLayout(jsonObject.getString("specialty"),jsonObject.getString("output"),getString(R.string.subproject_finish_output_unit),"red",R.id.subproject_finish_output_value_tablelayout);
				outputAll = outputAll + Long.valueOf(jsonObject.getString("output"));
			}
			
			InitTableLayout(getString(R.string.subproject_output_all),String.valueOf(outputAll),getString(R.string.subproject_finish_output_unit),"red",R.id.subproject_finish_output_value_tablelayout);
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
	}
	
	private void InitTableLayout(Object... params) {
		
		TableLayout table = (TableLayout) findViewById((Integer) params[4]);
		
		TextAppearanceSpan textappearancespan = null;
		
		if (params[3].equals("red")) {
			textappearancespan = new TextAppearanceSpan(this, R.style.listview_item_textview_red);   
		} else if(params[3].equals("black")) {
			textappearancespan = new TextAppearanceSpan(this, R.style.normalText);   
		} else if(params[3].equals("white")) {
			textappearancespan = new TextAppearanceSpan(this, R.style.listview_item_textview_while);   
		}
		
		TableRow row = new TableRow(this); 
		row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		
		TextView t = new TextView(this);
		t.setGravity(Gravity.CENTER_HORIZONTAL);
		SpannableStringBuilder style=new SpannableStringBuilder((CharSequence) params[0]);
		style.setSpan(textappearancespan,0,0,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		t.setText(style);
		
		row.addView(t);

		TextView t2 = new TextView(this);
		t2.setGravity(Gravity.CENTER_HORIZONTAL);
		SpannableStringBuilder style1=new SpannableStringBuilder((CharSequence) params[1]);
		style1.setSpan(textappearancespan,0,0,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		t2.setText(style1);
		
		row.addView(t2);
		
		TextView t3 = new TextView(this);
		t3.setGravity(Gravity.CENTER_HORIZONTAL);
		SpannableStringBuilder style2=new SpannableStringBuilder((CharSequence) params[2]);
		style2.setSpan(textappearancespan,0,0,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		t3.setText(style2);
		
		row.addView(t3);
		
		table.addView(row,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));   

	}
	
	
	private void InitRealWorkload() {
		String data = getCurProject().getWorkItemQuantity();
		try {
			JSONArray jsonArray = new JSONArray(data);
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				InitTableLayout(jsonObject.getString("workItemName"),jsonObject.getString("quantity"),jsonObject.getString("workItemUnit"),"red",R.id.subproject_real_workload_tablelayout);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	private void doIntent() {
		Intent intent = getIntent();
		SetProjectToApplication(intent.getStringExtra(Config.PROJID),intent.getStringExtra(Config.FROMWHERE));
		InitButton();
	}
	
	private void InitButton() {
		Button button = (Button) findViewById(R.id.subproject_list_button);
		button.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(ProjectDetailActivity.this,SubProjectListActivity.class);
				startActivity(intent);
			}
		});
	}
	
	private void SetProjectToApplication(String projectid,String from) {
		Project project = null;
		
		if (from.equals("log")) {
			project = getProjectByProjectid(projectid);
		} else if(from.equals("network")) {
			project = projectSearchServiceDb.getProjectByProjectId(projectid);
		}
		
		MyApplication myApplication = (MyApplication) this.getApplication();
		
		ProjectSearchLog log = new ProjectSearchLog();
		log.setName(project.getName());
		log.setBudget(project.getBudget());
		log.setOutput(project.getOutput());
		log.setProjectid(project.getProjectId());
		
		List<ProjectSearchLog> projectSearchLogs = projectSearchServiceDb.findLog();
		
		boolean one = true;
		
		if (projectSearchLogs.size() > 0 && projectSearchLogs.size() < 5) {
			for (ProjectSearchLog projectSearchLog : projectSearchLogs) {
				String projid = projectSearchLog.getProjectid();
				if (projid.equals(project.getProjectId())) {
					one = false;
				}
			}
			
			if (one) {
				if (projectSearchLogs.size() == 4) {
					projectSearchServiceDb.delLog(projectSearchLogs.get(3).getProjectid());
				}
				projectSearchServiceDb.saveLog(log);
			}
			
		} else {
			projectSearchServiceDb.saveLog(log);
		}
		
		myApplication.setProject(project);
	}
	
	private Project getProjectByProjectid(String projectid) {
		String result = null;
		try {
			result = new ProjectSearchTask(this).execute(getServerAddress(),projectid,"byid",getUser().getUsername()).get();
			if(result.equals("error")){
				Toast.makeText(this,getString(R.string.serverAddress_alert_addressError), Toast.LENGTH_LONG).show();  
				return null;
			}else if(result.equals("NoData")){
				Toast.makeText(this,getString(R.string.project_no_find_data), Toast.LENGTH_LONG).show();  
				return null;
			}else if(result != null){
				return ProcessData(result);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return null;
	}

	private Project ProcessData(String data) {
		try {
			JSONArray jsonArray = new JSONArray(data);
			Project project = new Project();
			for (int i = 0; i<jsonArray.length(); i++) {  
				JSONObject jsonObject = (JSONObject) jsonArray.get(i);  
			    project.setProjectId(jsonObject.getString("id"));
			    project.setName(jsonObject.getString("projName"));
			    project.setStartDate(jsonObject.getString("startDate"));
			    project.setFinishDate(jsonObject.getString("finishDate"));
			    project.setProjectType(jsonObject.getString("projectType"));
			    project.setArea(jsonObject.getString("area"));
			    project.setResponsibleDivision(jsonObject.getString("responsibleDivision"));
			    project.setBudget(jsonObject.getString("budget"));
			    project.setOutput(jsonObject.getString("output"));
			    project.setExpenditure(jsonObject.getString("expenditure"));
			    project.setOwnerInfo(jsonObject.getString("ownerInfo"));
			    project.setSupervisorInfo(jsonObject.getString("supervisorInfo"));
			    project.setDesignerInfo(jsonObject.getString("designerInfo"));
			    project.setContractNumber(jsonObject.getString("contractNumber"));
			    project.setSubProjectNum(jsonObject.getString("subProjectNum"));
			    project.setSubProjectFinishedNum(jsonObject.getString("subProjectFinishedNum"));
			    project.setSubProjectNoFinishedNum(jsonObject.getString("subProjectNoFinishedNum"));
			    project.setWorkItemQuantity(jsonObject.getString("workItemQuantity"));
			    project.setSpecialtyOutput(jsonObject.getString("specialtyOutput"));
			    projectSearchServiceDb.saveProject(project);
		    }
			return project;
		} catch (JSONException e) {
			e.printStackTrace();  
			Toast.makeText(this, getString(R.string.project_search_failure), Toast.LENGTH_LONG).show();  
		}
		return null;
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			this.finish();
			finishActivityPushUpIn();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
